package com.yanqu.road.server.manager.activity.jiuzhou.chat;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.manager.activity.jiuzhou.CrossJiuZhouMgr;
import com.yanqu.road.server.manager.activity.jiuzhou.activity.CrossJiuZhouActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossJiuZhouChatLogic {

    public static final int MAX_MESSAGE_COUNT = 50;
    private ActivityInfo activityInfo;
    private final Map<Integer, Map<Long, Map<Integer, WorldMessageProto.WorldMessageListMsg.Builder>>> chatMap = new ConcurrentHashMap<>();

    public CrossJiuZhouChatLogic(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
    }

    public void chat(int roomId, long chatUserId, int type, WorldMessageProto.WorldMessageTempMsg chatMsg) {
        CrossJiuZhouActivity activity = CrossJiuZhouMgr.getActivity(activityInfo.getActivityId());
        if (activity == null) {
            return;
        }

        chatMap.computeIfAbsent(roomId, k -> new ConcurrentHashMap<>())
                .computeIfAbsent(chatUserId, k -> new ConcurrentHashMap<>())
                .compute(type, (k, v) -> {
                    if (v == null) {
                        v = WorldMessageProto.WorldMessageListMsg.newBuilder();
                    }
                    // 限制消息列表的大小
                    while (v.getDataListCount() >= MAX_MESSAGE_COUNT) {
                        v.removeDataList(0);
                    }
                    v.addDataList(chatMsg);
                    return v;
                });
        // 消息同步
         activity.syncChat(roomId, chatUserId, chatMsg);
    }

    public List<WorldMessageProto.WorldMessageTempMsg> getChatMsg(int roomId, long chatUserId) {
        List<WorldMessageProto.WorldMessageTempMsg> dataList = new ArrayList<>();
        Map<Long, Map<Integer, WorldMessageProto.WorldMessageListMsg.Builder>> userMap = chatMap.get(roomId);
        if (userMap != null) {
            Map<Integer, WorldMessageProto.WorldMessageListMsg.Builder> typeMap = userMap.get(chatUserId);
            if (typeMap != null) {
                typeMap.values().forEach(builder -> dataList.addAll(builder.getDataListList()));
            }
        }
        return dataList;
    }

    public void clearRoomChat(int roomId) {
        chatMap.remove(roomId);
    }
}
